<template>
  <div>
    <router-view></router-view>
    <Layout />
    <audio
      class="audio"
      id="audio"
      ref="audio"
      v-if="musicSrc"
      autoplay
      :src="musicSrc"
      @pause="audioPause"
      @play="audioPlay"
      @timeupdate="timeupdate"
      @canplay="canplay"
      @ended="ended"
      controls
    ></audio>
  </div>
</template>

<script>
import Layout from './Layout.vue'

import { getSongs } from '../../request/api'
import { mapState, mapMutations } from 'vuex'

export default {
  components: {
    Layout,
  },

  data() {
    return {
      musicSrc: '',
    }
  },

  computed: {
    ...mapState({
      musicIdList: state => state.mmusic.musicIdList,
      play: state => state.mmusic.play,
    }),
  },

  watch: {
    musicIdList(n, o) {
      this.setPlay(false)
      const id = n[0]
      getSongs.getUrl({ id }).then(res => (this.musicSrc = res.data[0].url))
    },

    play(n, o) {
      if (n && this.$refs['audio'].paused) {
        this.$refs['audio'].play()
      }
      if (!n && !this.$refs['audio'].paused) {
        this.$refs['audio'].pause()
      }
    },
  },

  methods: {
    ...mapMutations('mmusic', ['setPlay', 'setMusicTotal', 'setMusicCurrent', 'InitMusicIdList']),

    //加载完成
    canplay() {
      this.$refs['audio'].play()
      this.setMusicTotal(this.$refs['audio'].duration)
    },

    //播放更新
    timeupdate() {
      this.setMusicCurrent(this.$refs['audio'].currentTime)
    },

    //播放完毕
    ended() {
      this.setPlay(false)

      if (this.musicIdList.length == 1) {
        document.getElementById('audio').load()
        return
      }

      const arr = [...this.musicIdList]
      const i = arr.pop()
      arr.unshift(i)
      this.InitMusicIdList(arr)
    },

    audioPause() {
      this.setPlay(false)
    },

    audioPlay() {
      this.setPlay(true)
    },
  },
}
</script>

<style lang="less" scoped>
audio {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10000;
  display: none;
}
</style>
